package com.sansecy.customview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class CalibrationView extends View {

    private Paint mPaint;
    private int mMeasuredWidth;
    private int mMeasuredHeight;
    private int mItemWidth;
    private int mSelectedPosition = 2;
    private int mSelectedColor;
    private int dp3;
    private int mDp30;

    public CalibrationView(Context context) {
        this(context, null);
    }

    public CalibrationView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mPaint.setColor(Color.WHITE);
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        dp3 = (int) (scaledDensity * 3);
        mDp30 = (int) (scaledDensity * 30);
        mPaint.setStrokeWidth(dp3);
        mPaint.setStyle(Paint.Style.STROKE);
        mSelectedColor = Color.parseColor("#FFCF00");
    }

    private float ratio;

    public void setDelta(float delta, float total) {
        ratio = delta / total;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mMeasuredHeight = getMeasuredHeight();
        mMeasuredWidth = getMeasuredWidth();
        mItemWidth = mMeasuredWidth / 8;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int itemWidth = mMeasuredWidth / 8;
        int canMoveWidth = mMeasuredWidth - itemWidth * 2;
        int center = mMeasuredWidth / 2;
        int widgetCenterX = (int) (center + ratio * canMoveWidth / 2);

        for (int i = 1; i < 8; i++) {
            int startX = mItemWidth * i;
            if (widgetCenterX == startX) {
                mPaint.setColor(mSelectedColor);
                canvas.drawLine(startX, 0, startX, mMeasuredHeight, mPaint);
            } else {
                int halfItemWidth = itemWidth / 2;
                int startXLeft = startX - halfItemWidth;
                int startXRight = startX + halfItemWidth;
                if ((widgetCenterX < startX && widgetCenterX >= startXLeft)) {
                    mPaint.setColor(mSelectedColor);
                    canvas.drawLine(startX, 0, startX, mMeasuredHeight, mPaint);
                } else if (widgetCenterX > startX && widgetCenterX < startXRight) {
                    mPaint.setColor(mSelectedColor);
                    canvas.drawLine(startX, 0, startX, mMeasuredHeight, mPaint);
                } else {
                    mPaint.setColor(Color.WHITE);
                    canvas.drawLine(startX, dp3, startX, mMeasuredHeight, mPaint);
                }
            }
        }
    }
}
